package com.example.myapplication.wifi

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import com.example.myapplication.Constants
import com.example.myapplication.ScanWifiResult
import com.example.myapplication.utils.Timber
import com.example.myapplication.wifi.WifiUtil.wifiManager

/** wifi扫描结果接收器，用于接收wifi扫描结果 */
object WifiScanResultReceiver : BroadcastReceiver() {
    lateinit var scanWifiResult: ScanWifiResult

    @SuppressLint("MissingPermission")
    override fun onReceive(context: Context, intent: Intent) {
        Timber.fi("----intent.action：${intent.action}")
        if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION == intent.action) {
            var scanResults = wifiManager.scanResults
            Timber.fi("收到wifi扫描结果: ${scanResults?.size}, 想要连接的wifi是：${Constants.wifiName}")
            val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)
            if(success){
                val results: List<ScanResult> = wifiManager.scanResults
                Timber.fi("扫描成功,结果：${results.size}")
//                val wifiInfos = WifiUtil.getScanWifiResult(results)
//                wifiInfos?.forEach {
//                    Timber.fi("扫描的wifi名称：${it.name}，wifi信号强度：${it.rssi}")
//                }
                scanWifiResult.success(results)
            }else {
                // 扫描到结果后，10秒后又再次扫描
                WifiScanHandler.delayScan()
            }
            Timber.fi("${WifiUtil.getWifiName()} ${if (WifiUtil.isWifiConnected()) "已连接" else "未连接"}")
            if (WifiUtil.isWifiConnected() && WifiUtil.getWifiName() == Constants.wifiName) {
                Timber.fi("需要的Wifi(${Constants.wifiName})本来就连接好了")
                return
            }

            if (scanResults == null || scanResults.size == 0) {
                return
            }

            for (scanResult in scanResults) {
//                Timber.fi("扫描到wifi：${scanResult.SSID}")
                if (scanResult.SSID == Constants.wifiName) {
                    Timber.fi("扫描到指定的Wifi了：$Constants.wifiName")
                    WifiUtil.connectToWiFi(Constants.wifiName, Constants.wifiPwd)
                    break
                }
            }
        }
    }

    fun setOnResult(scanResult: ScanWifiResult){
        this.scanWifiResult = scanResult
    }
}